<template>
  <div class="system-nav-page">
    <el-container class="nav-box">
      <el-header>
        <el-row>
          <el-col class="logo-box" :span="6">
            <!-- 这个icon我也不知道是啥，感觉好像没用，
            还占了位置让logo和下边没有对齐我就给注释了 -->
            <!-- <icon-font
              class="nav-logo"
              style="visibility: hidden;"
              icon="icon-global-001"
            /> -->
            <span class="logo-name">
              <img :src="active_logo" alt="logo">
            </span>
          </el-col>
          <el-col :span="18" class="user-info" style="padding-right:16px;">
            <el-dropdown>
              <div class="el-dropdown-link position">
                <div class="positionInfo">
                  <span v-if="positionCompanyName !=='null' ">{{ positionCompanyName }}</span>
                  <span v-if="companyName !== 'null' ">{{ companyName }}</span>
                  <span>{{ positionName || '' }}</span>
                </div>
                <i
                  v-if="positionList.length"
                  class="el-icon-arrow-down el-icon--right"
                />
              </div>
              <el-dropdown-menu slot="dropdown" v-if="positionList.length">
                <el-dropdown-item
                  v-for="(item, index) in positionList"
                  :key="index"
                  @click.native="choosePosition(item.companyId)"
                  style="display:flex; flex-direction:column; text-align:right;"
                >
                  <span>{{ item.companyName || '' }}</span>
                  <span>{{ item.positionName || '' }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown @command="handleDropdown">
              <span class="el-dropdown-link">
                {{ $store.state.userName || '--' }}
                <i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="userInfo">个人中心</el-dropdown-item>
                <el-dropdown-item
                  v-if="showCompanyCenter"
                  command="enterPriseCenter"
                  >企业中心</el-dropdown-item
                >
                <el-dropdown-item command="logout">退出</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </el-header>
      <el-main v-loading="allPageLoading">
        <ul
          class="system-classify-box"
          v-for="item in sysGroups"
          :key="item.appGroupCode"
        >
          <li class="classify-title">
            <span></span>
            <!-- <icon-font
              :icon="'icon-apps-group-' + item.appGroupCode"
            ></icon-font> -->
            {{ item.appGroupName }}
          </li>
          <div class="classify-list">
            <li
              class="classify-item"
              v-for="it in item.appList"
              :key="it.postInstId"
            >
            <!-- 基础资料模块 -->
            <el-card class="card-basics" v-if="item.appGroupCode === '0001'" shadow="hover" @click.native="toSystem(it)">
              <div class="system-icon-basics" :style="bagColor(it)">
                <!-- <icon-font :icon="(it.appLogo && it.appLogo.trim()) || 'el-icon-setting'"/> -->
                <m-iconfont :icon="(it.appLogo && it.appLogo.trim()) || 'el-icon-setting'"  :size="'38'" />
              </div>
              <div class="system-name-box-basics">
                <p class="system-name">{{ it.appName }}</p>
                <p class="system-desc">{{ it.appDesc || '暂无描述' }}</p>
              </div>
            </el-card>
            <!-- 非基础资料模块 -->
            <el-card class="card-no-basics" v-else shadow="hover" @click.native="toSystem(it)">
              <div class="system-icon-not-basics">
                <m-iconfont color="#4d84ff" :size="calcSize(it)" :style="specialIcon(it)" :icon="(it.appLogo && it.appLogo.trim()) || 'el-icon-setting'" />
                <!-- <icon-font :icon="(it.appLogo && it.appLogo.trim()) || 'el-icon-setting'" :style="specialIcon(it)"/> -->
              </div>
              <p class="system-name">{{ it.appName }}</p>
            </el-card>
            </li>
          </div>
        </ul>
        <div class="system-no-data" v-if="!sysGroups.length">
          暂无分配系统，请联系管理员！
        </div>
      </el-main>
    </el-container>
    <!-- 修改密码 -->
    <el-dialog
      class="dialog-password"
      :title="activeTitle"
      width="500px"
      :before-close="dialogClose"
      :visible.sync="detailVisible"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="通过密码验证修改" name="first">
          <el-form
            :model="pass"
            :rules="rules"
            label-position="right"
            label-width="132px"
            ref="ruleForm"
          >
            <el-form-item prop="userName" label="用户名">
              <el-input
                maxlength="20"
                placeholder="用户名"
                v-model="pass.userName"
                type="text"
                :disabled="true"
                clearable
              />
            </el-form-item>
            <el-form-item prop="oldPassword" label="原密码">
              <el-input
                maxlength="16"
                placeholder="请输入原密码"
                v-model="pass.oldPassword"
                autocomplete="new-password"
                type="password"
                clearable
                show-password
              />
            </el-form-item>
            <el-form-item prop="newPassword" label="新密码">
              <el-input
                placeholder="请输入新密码"
                maxlength="16"
                v-model="pass.newPassword"
                autocomplete="new-password"
                type="password"
                clearable
                show-password
              />
            </el-form-item>
            <el-form-item prop="newPasswordSecond" label="确认密码">
              <el-input
                placeholder="确认密码"
                maxlength="16"
                type="password"
                v-model="pass.newPasswordSecond"
                autocomplete="new-password"
                clearable
              />
            </el-form-item>
          </el-form>
          <div class="foot">
            <el-button
              type="primary"
              class="submit"
              @keyup="submit"
              @click="submit"
              >提交</el-button
            >
            <el-button class="submit" @keyup="reset" @click="resetPwdForm"
              >重置</el-button
            >
          </div>
        </el-tab-pane>
        <el-tab-pane label="通过手机验证修改" name="second">
          <el-form
            :model="phoneCode"
            :rules="PhoneRules"
            label-position="right"
            label-width="132px"
            ref="phoneForm"
          >
            <el-form-item prop="loginName" label="用户名">
              <el-input
                type="text"
                v-model="phoneCode.loginName"
                placeholder="请输入用户名"
                autocomplete="new-password"
                :disabled="true"
                clearable
              />
            </el-form-item>
            <el-form-item prop="password" label="新密码">
              <el-input
                maxlength="20"
                placeholder="请输入新密码"
                v-model="phoneCode.password"
                type="password"
                autocomplete="new-password"
                clearable
                show-password
              />
            </el-form-item>
            <el-form-item prop="passwordSecond" label="确认密码">
              <el-input
                maxlength="16"
                placeholder="确认密码"
                v-model="phoneCode.passwordSecond"
                autocomplete="new-password"
                type="password"
                clearable
                show-password
              />
            </el-form-item>
            <!-- <el-form-item prop="phone" label="手机号">
              <el-input
                placeholder="手机号"
                maxlength="16"
                v-model="phoneCode.phone"
                autocomplete="new-password"
                type="password"
                clearable
              />
            </el-form-item> -->
            <el-form-item prop="code" label="手机短信验证码" class="pCode">
              <el-input
                placeholder="手机短信验证码"
                maxlength="16"
                type="text"
                v-model="phoneCode.code"
                autocomplete="new-password"
                clearable
              />
              <el-button
                class="getCode"
                @click="sendCode"
                type="primary"
                :loading="codeLoading"
                :disabled="sendCodeDiabled"
                maxlength="6"
                >{{ sendCodeTitle }}</el-button
              >
            </el-form-item>
          </el-form>
          <div class="foot">
            <el-button
              type="primary"
              class="submit"
              @keyup="phoneSubmit"
              @click="phoneSubmit"
              >提交</el-button
            >
            <el-button class="submit" @keyup="reset" @click="resetPhoneForm"
              >重置</el-button
            >
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 用户信息 -->
    <el-dialog
      title="个人中心"
      :visible.sync="userInfoVisible"
      class="person-dialog-box"
      width="960px"
      top="10vh"
      @close="resetUserInfoForm"
    >
      <div class="title_list">
        <div
          v-for="(item, index) in titleList"
          :key="index"
          :class="{activeDiv: index === titleNumber}"
          @click="titleTab(index)"
        >
          {{ item.title }}
          <span class="activeBorder" v-show="index === titleNumber"></span>
        </div>
      </div>
      <main>
        <div class="userContent" v-show="titleNumber === 0">
          <el-form
            ref="userInfoForm"
            :model="userInfoForm"
            inline
            label-width="80px"
            :rules="userInfoFormRules"
            label-position="top"
          >
            <div class="userName">
              用户名
              <span>{{ userInfoForm.loginName }}</span>
            </div>
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="userInfoForm.phone"
                placeholder="请输入"
                clearable
                maxlength="11"
                :width="387"
              />
            </el-form-item>
            <el-form-item label="邮箱" prop="mail">
              <el-input
                v-model="userInfoForm.mail"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
            <el-form-item label="姓名" prop="userName">
              <el-input
                v-model="userInfoForm.userName"
                placeholder="请输入"
                clearable
                maxlength="16"
              />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userInfoForm.gender" placeholder="请选择">
                <el-option
                  v-for="item in gender"
                  :key="item.val"
                  :label="item.lab"
                  :value="item.val"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div v-show="titleNumber === 0"></div>
        </div>
        <div class="userContent" v-show="titleNumber === 1">
          <el-form
            ref="identityInfoForm"
            :model="identityInfoForm"
            inline
            label-width="80px"
            :rules="identityInfoFormRules"
            label-position="top"
            :disabled="editDisable"
          >
            <div class="userName">
              <div>
                姓名
                <span>{{ userInfoForm.userName }}</span>
              </div>
              <div>
                性别
                <span>{{ userInfoForm.genderStr }}</span>
              </div>
            </div>
            <el-form-item label="民族" prop="nation">
              <el-input
                v-model="identityInfoForm.nation"
                placeholder="请输入"
                clearable
                maxlength="11"
                :width="387"
              />
            </el-form-item>
            <el-form-item label="出生日期" prop="birth">
              <el-input
                v-model="identityInfoForm.birth"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
            <el-form-item label="身份证号" prop="idNumber">
              <el-input
                v-model="identityInfoForm.idNumber"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
            <el-form-item label="住址" prop="address">
              <el-input
                v-model="identityInfoForm.address"
                placeholder="请输入"
                maxlength="99"
              />
            </el-form-item>
            <el-form-item label="签发机关" prop="issuingAuthority">
              <el-input
                v-model="identityInfoForm.issuingAuthority"
                placeholder="请输入"
                clearable
                maxlength="16"
              />
            </el-form-item>
            <el-form-item label="有效期" prop="expiryDate">
              <el-input
                v-if="btnNumber === 0"
                v-model="expiryDateForm"
                placeholder="请输入"
                clearable
                maxlength="16"
              />
              <el-date-picker
                v-else
                v-model="identityInfoForm.expiryDate"
                type="daterange"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
              <!-- value-format="yyyy-MM-dd" -->
            </el-form-item>
            <el-form-item label="身份证照片" prop="userName">
              <div class="photo_box">
                <!-- 我是正面 1 -->
                <PictureUpload
                  :imgStr1="identityInfoForm.idPhoto[0]"
                  @RequestUpload="uploadSuccessaaa"
                  :Identificationone="Identificationones"
                ></PictureUpload>
                <!-- 我是反面 2-->
                <PictureUpload
                  :imgStr2="identityInfoForm.idPhoto[1]"
                  @RequestUpload="uploadSuccessaaa"
                  :Identificationtwo="Identificationtwos"
                ></PictureUpload>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="userContent" v-show="titleNumber === 2">
          认证状态： {{ personIfCertification ? '已认证' : '未认证' }}
          <el-button
            type="text"
            v-if="!personIfCertification"
            @click="goCertification"
            >去认证</el-button
          >
        </div>
      </main>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="titleNumber === 0"
          type="primary"
          @click.stop="updateUserInfo"
          :loading="userInfoLoading"
          >确定</el-button
        >
        <el-button
          type="primary"
          v-if="titleNumber === 2"
          @click="closeCertification"
          >确定</el-button
        >
        <div
          ref="operation_switching"
          class="operation_switching"
          v-if="titleNumber === 1"
        >
          <el-button
            type="primary"
            @click.stop="btnNumber === 0 ? editEvent() : identityInformation()"
            :loading="userInfoLoading"
            >{{ btnNumber === 0 ? '编辑' : '确定' }}</el-button
          >
        </div>
      </div>
    </el-dialog>
    <CertificationComfirmDialog
      ref="certification"
      @update="queryPersonalCertification"
    ></CertificationComfirmDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import auth from '@mixins/auth';
import {
  getCurrentApps,
  chooseApps,
  UcMerchantUserGetById,
  updateUserPassword,
  UcMerchantUserUpdate,
  orderBackUcMerchantIdentityUsergetById,
  orderBackUcMerchantIdentityUserupdate,
  sendVerificationCodeByLoginName,
  updatePasswordByPhone
} from '@const/api_staffCenter.js';
import {
  username,
  realName,
  password,
  phone,
  email,
  checkIdCard
} from '@const/formValidate.js';
import md5 from 'js-md5';
import { hasIn } from 'lodash';
import PictureUpload from '@components/pictureUpload';
import CertificationComfirmDialog from '@/moduleComponents/certification-confirm-dialog';
import cookie from 'js-cookie';
import {
  fddWebQueryPersonalCertification,
  fddWebApplyPersonalCertification
} from '@const/api_interfaceCenter';
const TIME_COUNT = 60;
export default {
  mixins: [auth],
  layout: 'blank',
  components: { PictureUpload, CertificationComfirmDialog },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入原密码'));
      } else {
        callback();
      }
    };
    var validatePassUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        callback();
      }
    };
    var validatePhoneCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机短信验证码'));
      } else {
        callback();
      }
    };
    var validateNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else if (value === this.pass.oldPassword) {
        callback(new Error('不能与原密码相同'));
      } else {
        callback();
      }
    };
    var validatePassSecond = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.pass.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validatePhoneCodeSecond = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.phoneCode.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    let checkUserName = [{ validator: validatePassUserName, trigger: 'blur' }];
    let checkPhone = [{ validator: validatePhone, trigger: 'blur' }];
    let checkCode = [{ validator: validatePhoneCode, trigger: 'blur' }];
    let check = [
      { validator: validatePass, trigger: 'blur' },
      { pattern: /^[0-9a-zA-Z]{6,16}$/, message: '密码为6-16位数字或字母' }
    ];
    let checkNewPass = [
      { validator: validateNewPass, trigger: 'blur' },
      { pattern: /^[0-9a-zA-Z]{6,16}$/, message: '密码为6-16位数字或字母' }
    ];
    return {
      app_backgroung_img: require('@assets/img/pc-other_zixtgbg@2x.png'),
      active_logo: require('@assets/img/login/pc-caise-logo.png'),
      Identificationones: '1',
      Identificationtwos: '2',
      prodata: {},
      activeTitle: '修改密码',
      detailVisible: false, // 修改密码弹框
      userInfoLoading: false,
      userInfoVisible: false, // 个人信息弹框
      gender: [{ lab: '男', val: 1 }, { lab: '女', val: 2 }],
      phoneCode: {
        loginName: cookie.get('userName'),
        password: '',
        passwordSecond: '',
        phone: '',
        code: ''
      },
      PhoneRules: {
        loginName: checkUserName,
        password: checkNewPass,
        passwordSecond: [
          { validator: validatePhoneCodeSecond, trigger: 'blur' }
        ],
        phone: checkPhone,
        code: checkCode
      },
      pass: {
        userName: cookie.get('userName'),
        oldPassword: '',
        newPassword: '',
        newPasswordSecond: ''
      },
      rules: {
        userName: checkUserName,
        oldPassword: check,
        newPassword: checkNewPass,
        newPasswordSecond: [{ validator: validatePassSecond, trigger: 'blur' }]
      },
      // 个人信息验证规则
      userInfoFormRules: {
        loginName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        userName: realName(),
        // password: password(),
        phone: phone(),
        mail: email(),
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
      },
      // 个人信息表单内容
      userInfoForm: {
        loginName: '呀呀呀',
        password: '',
        userName: '',
        phone: '',
        gender: '',
        genderStr: '',
        mail: '',
        idCard: ''
      },
      // 完善身份信息规则
      identityInfoFormRules: {
        nation: [{ required: true, message: '请输入民族' }],
        birth: [{ required: true, message: '请输入出生日期' }],
        idNumber: [
          {
            required: true,
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '你的身份证格式不正确'
          }
        ],
        address: [{ required: true, message: '请输入住址' }],
        issuingAuthority: [{ required: true, message: '请输入身份证签发机关' }],
        expiryDate: [{ required: true, message: '请选择身份证有效期限' }],
        idPhoto: [{ required: true, message: '请上传照片' }]
      },
      expiryDateForm: '',
      // 完善身份信息表单
      identityInfoForm: {
        nation: '汉族', // 民族
        birth: '1993-01-01', // 出生
        idNumber: '353535353535353535', //身份证
        address: '北京市朝阳区', //住址
        issuingAuthority: '浙江省杭州市', //签发机关
        expiryDate: ['', ''], // 有效期限
        idPhoto: ['', ''] // 身份证照片
      },
      allPageLoading: false, // 页面loading
      sysGroups: [], // 系统列表
      // 个人信息tab
      titleList: [
        { title: '修改个人信息', val: 1 },
        { title: '完善身份证信息', val: 2 },
        { title: '电子签章认证', val: 3 }
      ],
      // tab样式判断
      titleNumber: 0,
      // btnText: '编辑',
      btnNumber: 0,
      // 编辑禁用
      editDisable: true,
      positionInfo: '',
      activeName: 'first',
      sendCodeTitle: '验证码',
      codeLoading: false,
      sendCodeDiabled: false,
      personIfCertification: false // 是否个人认证完成
    };
  },
  mounted() {
    console.log('=====process.env.ROUTER_BASE:', process.env.ROUTER_BASE);
    function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return false;
    }
    let code = getQueryVariable('code');
    if (code) {
      // cookie.set('wechatCode', code)
      cookie.set('bindWechatCode', code);
      window.location.href = '/#/systemSetup/personal';
      // this.$router.push({
      //   path: `/systemSetup/personal`
      // });
    }
    // 获取系统列表
    this.getSysList();
    let msg = this.$route.query.msg;
    msg && this.$message({ type: 'warning', message: decodeURIComponent(msg) });
    msg && (window.location.hash = '');
    this.$store.dispatch('getPositionList');
  },
  computed: {
    showCompanyCenter() {
      return (
        (this.$store.state.ifAdmin === 'true' &&
          this.$store.state.companyId !== '0') ||
        (this.$store.state.ifAdmin === true &&
          this.$store.state.companyId !== '0')
      );
    },
    ...mapState([
      'positionCompanyName',
      'companyName',
      'positionName',
      'positionList',
      'positionId'
    ]),
    showCompanyCode() {
      let companyCode = this.$store.state.companyCode;
      return companyCode && companyCode !== 'null';
    },
    // 计算多个公司的展示
    customCompanyName() {
      return this.$store.state.companyName !== 'null'
        ? this.$store.state.companyName || '平台管理员'
        : '平台管理员';
    }
  },
  watch: {
    companyName: {
      handler: function(val, oldVal) {
        this.positionInfo = val;
      },
      deep: true
    }
  },
  methods: {
    // 动态设置子系统特殊icon的大小
    specialIcon(item) {
      let styleObj = {};
      if (item.appLogo === 'iconbkdly') {
        styleObj = {
          'line-height': '60px',
          'font-size': '136px'
        };
      }
      if (item.appLogo === 'm-pc-menu_tairmlogo') {
        styleObj = {
          'line-height': '60px',
          'font-size': '60px'
        };
      }
      return styleObj;
    },
    // 准确设置size
    calcSize(item) {
      let size = '38';
      if (item.appLogo === 'iconbkdly') {
        size = '136';
      } else if (item.appLogo === 'm-pc-menu_maiddf') {
        size = '60';
      }
      if (item.appLogo === 'm-pc-menu_tairmlogo') {
        size = '60';
      }
      return size;
    },
    // 动态设置基础管理icon的背景色
    bagColor(item) {
      let bgColoe = {};
      if (item.appName === '企业认证') {
        bgColoe = {
          background: '#83E254',
          'box-shadow': '0 5px 12px 0 rgba(82,196,25,0.53)'
        };
      } else if (item.appName === '电子签章管理') {
        bgColoe = {
          background: '#FF6850',
          'box-shadow': '0 5px 12px 0 rgba(255,0,0,0.33)'
        };
      } else if (item.appName === '企业信息管理') {
        bgColoe = {
          background: '#FEB416',
          'box-shadow': '0 5px 12px 0 rgba(254,174,4,0.53)'
        };
      } else {
        bgColoe = {
          background: '#6DA6FF',
          'box-shadow': '0 5px 12px 0 rgba(109,166,255,0.53)'
        };
      }
      return bgColoe;
    },
    // 个人认证申请
    goCertification() {
      this.$axios.get(fddWebApplyPersonalCertification).then(res => {
        const { data } = res;
        if (!Number(data.code)) {
          const payload = data.payload;
          const applyPersonUrl = payload.fddUrl;
          this.$refs.certification.dialogVisible = true;
          window.open(applyPersonUrl, '_blank');
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 电子签章 个人认证查询
    async queryPersonalCertification() {
      const personInfo = await this.$axios.get(
        fddWebQueryPersonalCertification
      );
      this.personIfCertification = hasIn(personInfo, [
        'data',
        'payload',
        'ifCertification'
      ])
        ? personInfo.data.payload.ifCertification
        : false;
    },
    // 关闭认证
    closeCertification() {
      this.userInfoVisible = false;
    },
    // 更新个人信息
    updateUserInfo() {
      this.$refs['userInfoForm'].validate(valid => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: UcMerchantUserUpdate,
            data: {
              id: this.$store.state.userId,
              gender: this.userInfoForm.gender,
              genderStr:
                this.userInfoForm.genderStr === null
                  ? '--'
                  : this.userInfoForm.genderStr,
              loginName: this.userInfoForm.loginName,
              mail: this.userInfoForm.mail,
              phone: this.userInfoForm.phone,
              userName: this.userInfoForm.userName
            }
          }).then(res => {
            if (res.data.code === '0') {
              this.$message({ type: 'success', message: '修改成功!' });
              this.userInfoVisible = false;
            }
          });
        }
      });
    },
    // 获取个人信息
    getUserInfo() {
      this.userInfoVisible = true;
      (this.titleNumber = 0),
        (this.btnNumber = 0),
        // 编辑禁用
        (this.editDisable = true);
      this.$axios({
        method: 'get',
        url: UcMerchantUserGetById,
        params: {
          id: this.$store.state.userId
        }
      }).then(res => {
        if (res.data.code === '0') {
          let obj = hasIn(res, 'data.payload') ? res.data.payload : {};
          this.userInfoForm = obj;
        }
      });
    },
    // 重置个人信息
    resetUserInfoForm() {},
    getSysList() {
      console.log('==============getSysList============');
      this.allPageLoading = true;
      this.$axios({
        url: getCurrentApps,
        method: 'post',
        data: {}
      })
        .then(res => {
          if (res.data.code === '0') {
            let arr = hasIn(res, ['data', 'payload']) ? res.data.payload : [];
            this.sysGroups = arr;
            this.allPageLoading = false;
            console.log('======res.data.payload:', res.data.payload);
            // this.judgeLen(arr)
          }
        })
        .catch(() => {
          this.handleDropdown('logout');
          this.allPageLoading = false;
        });
    },
    // 完善身份信息编辑
    editEvent() {
      this.btnNumber = 1;
      this.editDisable = false;
    },
    uploadSuccessaaa(url, nnns) {
      if (nnns === '1') {
        this.identityInfoForm.idPhoto[0] = url; // 身份证照片正面
      } else {
        this.identityInfoForm.idPhoto[1] = url; // 有效期限片反面
      }
    },
    // orderBackUcMerchantIdentityUsergetById 获取身份证信息
    cardinformation() {
      this.$axios({
        method: 'get',
        url: `${orderBackUcMerchantIdentityUsergetById}?userId=${
          this.$store.state.userId
        }`,
        data: {
          userId: this.$store.state.userId
        }
      }).then(res => {
        if (res.data.code !== '0') return;
        let temporary = res.data.payload;
        this.identityInfoForm.userName = temporary.name;
        this.identityInfoForm.genderStr = temporary.genderStr;
        this.identityInfoForm.nation = temporary.nation;
        this.identityInfoForm.birth = temporary.birthDate;
        this.identityInfoForm.idNumber = temporary.identityId;
        this.identityInfoForm.address = temporary.address;
        this.identityInfoForm.issuingAuthority = temporary.issueOffice;
        this.identityInfoForm.expiryDate[0] =
          temporary.startDate === null ? '' : temporary.startDate; //开始时间 还需改动
        this.identityInfoForm.expiryDate[1] =
          temporary.endDate === null ? '' : temporary.endDate; //结束时间
        this.identityInfoForm.idPhoto[0] = temporary.identityFront; //身份正面
        this.identityInfoForm.idPhoto[1] = temporary.identityBack; //身份证反面
        if (temporary.startDate) {
          this.expiryDateForm =
            temporary.startDate.split(' ')[0] +
            '-' +
            temporary.endDate.split(' ')[0];
        } else {
          this.expiryDateForm = '';
        }
      });
    },
    // 完善身份信息更新  orderBackUcMerchantIdentityUserupdate  根据用户ID修改身份证信息 接口
    identityInformation() {
      // 需要添加正则判断  不改变时间是 2020-03-10 16:00:00  重新选择时间是 Wed Mar 18 2020 00:00:00 GMT+0800 (中国标准时间)  判断是不是以数字开头的 如果是则用模板字符串进行拼接 如果不是则不改变直接入参
      if (
        !(this.identityInfoForm.idPhoto[0] && this.identityInfoForm.idPhoto[1])
      ) {
        this.$message({
          type: 'warning',
          message: '请上传身份证照片'
        });
        return;
      }
      this.$refs['identityInfoForm'].validate(valid => {
        if (valid) {
          let verificationTimestart = `${
            this.identityInfoForm.expiryDate[0].split(' ')[0]
          } 16:00:00`;
          let verificationTimeend = `${
            this.identityInfoForm.expiryDate[1].split(' ')[0]
          } 16:00:00`;
          if (!(verificationTimestart && verificationTimeend)) {
            this.$message({
              type: 'warning',
              message: '请输入有效期'
            });
            return;
          }
          this.prodata.userId = this.$store.state.userId;
          this.prodata.nation = this.identityInfoForm.nation; // 民族
          this.prodata.birthDate = this.identityInfoForm.birth; // 出生
          this.prodata.identityId = this.identityInfoForm.idNumber; // 身份证
          this.prodata.address = this.identityInfoForm.address; // 住址
          this.prodata.issueOffice = this.identityInfoForm.issuingAuthority; // 签发机关
          this.prodata.startDate = verificationTimestart; // 有效期限
          this.prodata.endDate = verificationTimeend; // 有效期限
          this.prodata.identityFront = this.identityInfoForm.idPhoto[0]; // 正面
          this.prodata.identityBack = this.identityInfoForm.idPhoto[1]; // 反面
          this.prodata.gender = this.userInfoForm.gender; // 性别
          this.prodata.name = this.userInfoForm.userName; // 姓名
          // 请求
          this.$axios({
            method: 'post',
            url: orderBackUcMerchantIdentityUserupdate,
            data: this.prodata
          }).then(res => {
            this.userInfoVisible = false;
            this.$message({
              type: 'success',
              message: '上传成功',
              duration: 1000
            });
          });
        }
      });
    },
    // 判断长度是否大一一个
    judgeLen(arr) {
      if (!arr || !arr.length) {
        // window.location.href = '/business/index'
        this.showMessage('暂无分配系统，请联系管理员！');
      } else {
        // if (
        //   arr.length === 1 &&
        //   arr[0].appListInsts &&
        //   arr[0].appListInsts.length === 1
        // ) {
        //   this.showMessage('检测到只有一个系统，自动进入该系统！')
        //   let timer = setTimeout(() => {
        //     this.toSystem(arr[0].appListInsts[0])
        //   }, 1000)
        // }
      }
    },
    showMessage(msg, type = 'warning') {
      this.$message({
        type: type,
        message: msg
      });
    },
    handleDropdown(command) {
      if (command === 'logout') {
        this.$store.commit(command);
        this.$router.replace(this.$PATH_CONST.login_page);
      } else if (command === 'putPass') {
        this.detailVisible = true;
      } else if (command === 'userInfo') {
        // this.getUserInfo()
        // this.cardinformation()
        this.$router.push('/systemSetup/personal');
      } else if (command === 'enterPriseCenter') {
        this.toEnterpriseCenter();
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    reset() {
      console.log('tab, event');
    },
    // 短信验证码确定
    phoneSubmit() {
      this.$refs['phoneForm'].validate(valid => {
        if (valid) {
          let data = {
            loginName: this.phoneCode.loginName,
            newPassword: md5(this.phoneCode.passwordSecond),
            // phone: this.phoneCode.phone,
            verificationCode: this.phoneCode.code
          };
          this.submitLoading = true;
          this.$axios({
            url: updatePasswordByPhone,
            method: 'post',
            data
          })
            .then(res => {
              this.$message({ type: 'success', message: '密码修改成功' });
              this.$router.push(this.$PATH_CONST.login_page);
            })
            .finally(res => {
              this.submitLoading = false;
            });
        }
      });
    },
    resetPhoneForm() {
      this.$refs['phoneForm'].resetFields();
    },
    resetPwdForm() {
      this.$refs['ruleForm'].resetFields();
    },
    // 确定按钮
    submit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          let data = {
            id: this.$store.state.userId,
            password: md5(this.pass.oldPassword),
            newPassword: md5(this.pass.newPassword)
          };
          this.submitLoading = true;
          this.$axios({
            url: updateUserPassword,
            method: 'post',
            data
          })
            .then(res => {
              this.$message({ type: 'success', message: '密码修改成功' });
              this.$router.replace(this.$PATH_CONST.login_page);
              this.detailVisible = false;
              this.onClear();
            })
            .finally(res => {
              this.submitLoading = false;
            });
        }
      });
    },
    // 清空数据
    onClear() {
      this.pass = {
        oldPassword: '',
        newPassword: '',
        newPasswordSecond: ''
      };
    },
    dialogClose() {
      this.onClear();
      this.detailVisible = false;
    },
    toSystem(item) {
      // 针对泰尔茂子系统，需要拿到item.domain后边的MID参数，存到cookie里
      // window.location.href 获取地址
      let url1 = item.domain;
      let str = url1.split('?')[1];
      let params = new URLSearchParams(str);
      let MIDcode = params.get('MID');
      cookie.set('MID', MIDcode || '');

      if (!item.domain) {
        this.$message({ type: 'warning', message: '没有配置子系统地址' });
        return;
      }
      // 20200407现在不需要chooseApps了，直接通过appid调用资源菜单接口进入登录后的页面/worktable
      // 但是需要保存到cookie，不然刷新页面就没有了
      this.$store.commit('setAppId', item.id);
      this.$store.commit('setStructureLogo', item.overallStructureLogo);
      this.$store.commit('setFactoryCompanyId', item.factoryCompanyId);
      this.$store.commit('changeActiveNameArr', []);
      if (item.domain.indexOf('http') === -1) {
        this.$router.push(item.domain);
      } else {
        window.location.href = item.domain;
      }
      // this.$router.push('/worktable')
      // this.allPageLoading = true
      // this.$axios({
      //   url: chooseApps,
      //   method: 'post',
      //   data: {
      //     postInstId: item.postInstId,
      //     appId: item.appId
      //   }
      // }).then(res => {
      //   this.$store.commit('logout', false)
      //   let obj = hasIn(res, ['data', 'payload']) ? res.data.payload : {}
      //   this.$store.commit('login', obj)
      //   if (item.domain.indexOf('http') === -1) {
      //     this.$router.push(item.domain)
      //   } else {
      //     window.location.href = item.domain
      //   }
      // })
    },
    sendCode() {
      // if (!this.ruleForm.phone) {
      //   this.$message({type: 'warning', message: '请先输入手机号码'})
      //   return
      // }
      // this.ruleForm.phone = '17319299097'
      this.codeLoading = true;
      this.$axios({
        method: 'post',
        url: sendVerificationCodeByLoginName,
        data: {
          loginName: this.phoneCode.loginName
          // prefix: this.prefix
        }
      })
        .then(data => {
          if (data.data.code * 1 === 0) {
            this.$message({
              message: `验证码已下发到您尾号${
                data.data.payload
              }的手机号，请注意查收`,
              type: 'success'
            });
            // this.ruleForm.phone = data.data.payload
            this.countDown();
          }
        })
        .finally(() => {
          this.codeLoading = false;
        });
    },
    countDown() {
      if (this.sendCodeDiabled) return;
      this.sendCodeDiabled = true;
      this.count = TIME_COUNT;
      let timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          this.count--;
          this.sendCodeTitle = `${this.count}秒后重新获取`;
        } else {
          this.sendCodeTitle = '重新获取';
          this.timer = null;
          this.sendCodeDiabled = false;
          clearInterval(timer);
        }
      }, 1000);
    },
    titleTab(ind) {
      this.titleNumber = ind;
      // 个人签章认证状态查询
      if (ind === 2 && !this.personIfCertification) {
        this.queryPersonalCertification();
      }
    },
    // 切换岗位
    choosePosition(val) {
      if (this.positionId === val) {
        this.$message.error('当前已是该岗位');
        return false;
      }
      let item = {
        positionId: val
      };
      console.log(item, '==============');
      this.$store.dispatch('choosePosition', { item });
    },
    toEnterpriseCenter() {
      this.$router.push({ path: '/enterpriseCenter' });
    }
  }
};
</script>
<style lang="less">
@import '../m-front-common/pc/assets/var.less';
.system-nav-page {
  height: 100%;
  background-color: #f4f6fb;
  .nav-box {
    height: 100%;
    .el-header {
      padding: 0 48px;
      background-color: #fff;
      .logo-box {
        display: flex;
        align-items: center;
        .nav-logo {
          font-size: 45px;
          color: @themeBlue;
          vertical-align: middle;
        }
        .logo-name {
          height: 50px;
          background-color: #fff;
          font-size: 22px;
          color: @themeBlue;
          font-weight: bold;
          cursor: default;
          display: flex;
          align-items: center;
        }
      }
      .user-info {
        text-align: right;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .el-input__inner {
          border: none;
        }
        .position {
          display: flex;
          align-items: center;
          margin-right: 15px;
          .positionInfo {
            display: flex;
            flex-direction: column;
          }
        }
        .info-company {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
          margin-right: 30px;
        }

        .icon-group {
          width: 140px;
          display: flex;
          justify-content: space-evenly;

          .icon-btn {
            cursor: pointer;
          }

          .el-badge__content {
            border: none;
          }
        }
      }
    }
    .el-main {
      padding: 16px 48px;
      .system-classify-box {
        padding: 0;
        width: 100%;
        overflow: hidden;
        background-color: #fff;
        padding-bottom: 4px;
        margin-bottom: 16px;
        .classify-title {
          list-style: none;
          font-weight: 400;
          font-size: 18px;
          color: #333333;
          line-height: 54px;
          // margin: 24px 0 44px 26px;
          border-bottom: 1px solid #e6e6e6;
          margin-left: 20px;
          margin-bottom: 50px;
          display: flex;
          align-items: center;
          span {
            display: block;
            width: 3px;
            height: 19px;
            background: #4d84ff;
            margin-right: 10px;
          }
        }
        .classify-list {
          display: flex;
          flex-wrap: wrap;
          .classify-item {
            list-style: none;
            margin-bottom: 50px;
            width: 33%;
            display: flex;
            justify-content: center;
            align-items: center;
            .el-card {
              width: 324px;
              cursor: pointer;
              border-radius: 5px;
              border: none;
            }
            .card-basics {
              box-shadow: 0 0 6px 0 #c7d8ff;
              .el-card__body {
                // height: 132px;
                padding: 34px 20px;
                display: flex;
                align-items: flex-start;
                // --------基础资料的UI---------
                .system-icon-basics {
                  width: 64px;
                  height: 64px;
                  border-radius: 50%;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  .iconfont {
                    font-size: 38px;
                    color: #fff;
                  }
                }
                .system-name-box-basics {
                  margin-left: 18px;
                  .system-name {
                    font-size: 20px;
                    color: #333333;
                    font-weight: bold;
                    margin: 3px 0;
                  }
                  .system-desc {
                    width: 202px;
                    font-size: 14px;
                    color: #666666;
                  }
                }
              }
            }
            .card-no-basics {
              border: 1px solid #c0d3ff;
              background-image: url('../../m-front-common/pc/assets/img/pc-other_zixtgbg@2x.png');
              background-size: 100%;
              background-repeat: no-repeat;
              .el-card__body {
                height: 150px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 0;
                .system-icon-not-basics {
                  height: 60px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  .iconfont {
                    font-size: 38px;
                    color: #4d84ff;
                  }
                }
                .system-name {
                  font-size: 20px;
                  color: #333333;
                  font-weight: 700;
                  margin-top: 5px;
                }
              }
            }
            .card-basics:hover {
              box-shadow: 0 0 6px 0 #81a8ff;
            }
            .card-no-basics:hover {
              border: 1px solid #81a8ff;
              box-shadow: none;
            }
          }
        }
      }
      .system-no-data {
        font-size: 16px;
        text-align: center;
        padding: 15px;
        border-radius: 5px;
        margin: 30px 30%;
        border: 1px solid #ccc;
        color: #606266;
      }
    }
  }
  .el-tabs__nav-scroll {
    display: flex;
    justify-content: center;
  }
  .el-dialog__header {
    border: none;
  }
  .el-dialog__title {
    display: none;
  }
  .dialog-password {
    .el-dialog {
      .el-form-item__content {
        display: flex;
        .getCode {
          border: none;
          height: 34px;
          margin-top: 1px;
          margin-left: 5px;
        }
      }
    }
    .foot {
      text-align: center;
    }
  }
  .person-dialog-box {
    overflow: hidden;
    .el-dialog {
      position: relative;
      height: 540px;
      .el-dialog__header {
        border-bottom: 0;
        padding: 20px 0 0 20px;
      }
      .el-dialog__body {
        padding-top: 14px;
        padding-bottom: 0;
        .title_list {
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-bottom: 24px;
          div {
            font-size: 14px;
            color: #909db0;
            position: relative;
            cursor: pointer;
            margin-right: 32px;
            .activeBorder {
              position: absolute;
              width: 20px;
              background-color: rgba(35, 113, 197, 1);
              height: 2px;
              // left: 0px;
              left: 50%;
              bottom: -6px;
              transform: translate(-50%);
            }
          }
          .activeDiv {
            font-weight: 600;
            color: rgba(35, 113, 197, 1);
            font-size: 20px;
          }
        }
        .userContent {
          position: relative;
          height: 360px;
          overflow: auto;
          .userName {
            display: flex;
            color: #a7b1c7;
            font-size: 14px;
            margin-bottom: 32px;
            div {
              width: 387px;
            }
            span {
              color: #26344c;
              margin-left: 8px;
            }
          }

          margin-left: 92px;
          .el-form {
            .el-input {
              width: 357px !important;
            }
            .el-form-item.is-error {
              margin-bottom: 32px;
            }
          }
          .photo_box {
            display: flex;
          }
        }
        .el-form-item--medium {
          .el-form-item__label {
            line-height: 20px;
          }
        }
      }
      .el-dialog__footer {
        border-top: 0;
        .dialog-footer {
          text-align: center;
          .el-button--medium {
            padding: 15px 145px;
          }
        }
        .operation_switching {
          background: white;
        }
      }
    }

    .el-form {
      .el-input {
        width: 211px;
      }
    }

    .dialog-box {
      .el-input {
        width: 211px;
      }
    }
  }
}
</style>
